<?php

namespace control;
/*
*项目类
*/

class projectClass extends adIndexClass
{
    private const page  = 'project';
    private const table = 'project';
    private const title = '项目';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => "编码",
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'name'         => [
                        'name'  => '项目名称',
                        'width' => 200,
                    ],
                    'managerId'    => [
                        'name'  => '项目负责人',
                        'width' => 200,
                    ],
                    'tel'          => [
                        'name'  => '负责人电话',
                        'width' => 200,
                    ],
                    'startDate'    => [
                        'name'  => '开始日期',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'completeDate' => [
                        'name'  => '验收日期',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'text'         => [
                        'name'  => '备注',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "编码" => text(array("name" => "orderNo")),
                    "名称" => text(array("name" => "name")),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "<span onclick=\"layer('" . self::page . "','edit',{id:'" . self::getId() . "'})\" class='spanButton'>新增</span>\n";
        $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'del'})\">删除</span>\n";
        $button .=
            "<a href='" . root . "control/adIndex.html?cla=" . self::page . "&fun=downloadModel'><span class='spanButton'>导入模板</span></a>" .
            $this->upButton(array("title" => "导入", "fun" => "importData"));
        $button .= "  <a href='" . root . "control/adIndex.html?cla=" . self::page . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name"    => $this->post('name'),
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid
        );
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'startDate desc,time',
            "sort"   => $this->post('list_sort') ?: "asc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => "startDate desc,time asc"));
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        //获取自定义字段参数
        $installSearch = $this->installSearch(self::page . '-homeSearch');
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "box"  => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => self::title . "详情", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'managerId':
                        $row[] = self::findStaff($array['managerId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "项目编码：" => text(array('name' => 'orderNo', 'value' => $info['orderNo'])),
            ),
            array(
                must . "项目名称：" => text(array('name' => 'name', 'value' => $info['name'])),
            ),
            array(
                "负责部门：" => selectMultiple(array('name' => 'departmentId', 'value' => $info['departmentId'], 'title' => '请选择', 'table' => 'department', "order by time asc", 'sqlId' => 'id', 'sqlField' => 'name'))
            ),
            array(
                "负责人：" => selectMultiple(array('name' => 'managerId', 'value' => $info['managerId'], 'title' => '请选择', 'table' => 'staff', 'where' => "state !='离职' order by time asc", 'sqlId' => 'stid', 'sqlField' => 'name'))
            ),
            array(
                "手机号：" => text(array('name' => 'tel', 'value' => $info['tel'])),
            ),
            array(
                "开始日期：" => text(array('name' => 'startDate', 'laydate' => [], 'value' => $info['startDate'])),
            ),
            array(
                "验收日期：" => text(array('name' => 'completeDate', 'laydate' => [], 'value' => $info['completeDate'])),
            ),
            array(
                "备注：" => textarea(array('name' => 'text', 'value' => $info['text'], 'class' => 'textarea')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑", 'winFix' => true, "height" => 600, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'orderNo'      => $this->post('orderNo'),
            'name'         => $this->post('name'),
            'departmentId' => $this->post('departmentId'),
            'managerId'    => $this->post('managerId'),
            'tel'          => $this->post('tel'),
            'startDate'    => $this->post('startDate'),
            'completeDate' => $this->post('completeDate'),
            'text'         => $this->post('text'),
        ];
        $annotation = [
            'orderNo' => '项目编码',
            'name'    => '名称',
        ];
        $rules      = [
            'orderNo' => 'required',
            'name'    => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and orderNo = '$field[orderNo]' and id !='$id'")) > 0) {
            $json['warn'] = "已存在此项目编码";
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and name = '$field[name]' and id !='$id'")) > 0) {
            $json['warn'] = "已存在此项目名称";
        } else {
            $where = " id = '$id' ";
            $info  = query(self::table, $where);
            if (!$info['id']) {
                $field        = array_merge($field, [
                    'id'   => $id,
                    'stid' => $this->control['stid'],
                    'coid' => self::$coid,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['href']     = root . 'control/adIndex.html?cla=assistAccount&fun=home&menu=project';
                $json['warn']     = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr     = [];
            $sql    = static::rGet(self::$stid . self::page . 'sql');
            $title  = ["编码", "项目名称", "负责部门", "项目负责人", "负责人电话", "开始日期", "验收日期", '备注'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $department = query('department', "id = '$array[departmetnId]'");
                    $tr[]       = array($array['orderNo'], $array['name'], $department['name'], self::findStaff($array['managerId']), $array['tel'], $array['startDate'], $array['completeDate'], $array['text']);
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $title  = ["编码", "项目名称", "负责部门", "负责人编号", "项目负责人名称", "负责人电话", "开始日期", "验收日期", '备注'];
        $data[] = ['0001', '轨道交通10号线延长线项目', '工程部', 'YM20220101001', '张三', '13000000000', '2022-05-13', '2024-05-13', '测试数据'];
        $text   = $this->control['name'] . "下载了项目导入模板";
        $this->logText(["type" => self::page, "text" => $text]);
        $this->excelOut($title, $data, '项目导入模板.xlsx');
        exit(0);
    }

    /*数据导入分析*/
    public function importData()
    {
        $data = $this->importHead(format: [
            0=>\Vtiful\Kernel\Excel::TYPE_STRING
        ]);
        $x    = 0;
        $text = '';
        foreach ($data as $i => $row) {
            if ($i > 0) {
                $cell       = formSubArray($row);
                $department = query('department', "name = '$cell[2]'");
                $staff      = query('staff', "orderNo = '$cell[3]'");
                $field      = [
                    'orderNo'      => $cell[0],
                    'name'         => $cell[1],
                    'departmentId' => $department['id'],
                    'managerId'    => $staff['stid'],
                    'tel'          => $cell[5],
                    'startDate'    => $cell[6],
                    'completeDate' => $cell[7],
                    'text'         => $cell[8],
                ];

                $annotation = [
                    'orderNo' => '项目编码',
                    'name'    => '名称',
                ];
                $rules      = [
                    'orderNo' => 'required',
                    'name'    => 'required',
                ];
                // 校验是否符合规则
                $vt     = new \verify();
                $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                if ($result === false) {
                    $text .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and orderNo = '$field[orderNo]'")) > 0) {
                    $text .= "第【{$i}】行：已存在此项目编码<br>";
                } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and name = '$field[name]'")) > 0) {
                    $text .= "第【{$i}】行：已存在此项目名称<br>";
                } else {
                    $field = array_merge($field, [
                        'id'   => suiji(),
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $warn  = static::insert(["table" => self::table, "field" => $field]);
                    if (in_array($warn, ["新增成功", "更新成功"])) {
                        $x++;
                        $text .= "第【{$i}】行导入成功<br>";
                    } else {
                        $text .= "第【{$i}】行导入失败：编辑失败<br>";
                    }
                }
            }
        }
        $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
        $this->logText(["type" => self::page, "text" => $text]);
        $warn             = "成功导入" . $x . "条数据，详情请查看日志！";
        $_SESSION['warn'] = $warn;
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

// 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act      = '';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                break;
        }
        return $this->confirm([
            'title'    => $title,
            'function' => $function,
            'form'     => $form,
            'power'    => $power,
            'pwd'      => $pwd,
        ]);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
//                if ($info['state'] !='停用'){
//                    $warn = "删除失败：不是停用状态";
//                }else{
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
//                }
                $text .= self::title . "名称：【{$info['name']}】，ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

